package com.sinbad.consumer.receive.direct;

import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Log4j2
@Component
public class DirectModeReceive {

    /**
     * direct/路由模式
     *
     * @param message
     */
    @RabbitListener(queues = "directQueue")
    public void directMode(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try {
            //模拟异常
//            System.out.println("业务处理" + 10 / 0);

            /**
             * 无异常就确认消息
             * deliveryTag:取出来当前消息在队列中的的【索引】;
             * 每五条确认消息
             */
            System.out.println(deliveryTag);
            if (0 == deliveryTag % 5) channel.basicAck(deliveryTag, true);
            System.out.println("directMode开始消费消息：" + message);

        } catch (Exception e) {
            try {
                //有异常就绝收消息
                channel.basicNack(deliveryTag, false, true);
                //查看异常信息
                Thread.sleep(1000);

                System.err.println("directMode消费失败：" + message);
            } catch (IOException | InterruptedException ioException) {
                /*
                 * 一般实际异常情况下的处理过程：记录出现异常的业务数据，将它单独插入到一个单独的模块，
                 * 然后尝试3次，如果还是处理失败的话，就进行人工介入处理
                 */
                ioException.printStackTrace();
            }
        }

    }

}
